package com.github.wxiaoqi.security.admin.biz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import com.ace.cache.annotation.CacheClear;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.mapper.MenuMapper;
import com.github.wxiaoqi.security.admin.mapper.UserMapper;
import com.github.wxiaoqi.security.admin.vo.UserPassword;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.constant.UserConstant;
import com.github.wxiaoqi.security.common.crm.request.QueryPersonalBaseListRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 16:23
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserBiz extends BaseBiz<UserMapper,User> {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserAuthUtil userAuthUtil;
    @Override
    public int insertSelective(User entity) {
    	String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(entity.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
        entity.setPassword(password);
        return super.insertSelective(entity);
    }
    public Map<String, Object> add(Map<String, Object> param) throws Exception {
    	String crtUser = (String) param.get("crtUser");
    	String crtName = (String) param.get("crtName");
    	User entity = EntityUtils.map2Bean(param, User.class);
    	String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(entity.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
        entity.setPassword(password);
        entity.setCrtTime(new Date());
        entity.setUpdTime(new Date());
        entity.setCrtName(crtName);
        entity.setCrtUser(crtUser);
        entity.setUpdName(crtName);
        entity.setUpdUser(crtUser);
        mapper.addUser(entity);
        Map<String, Object> result = new HashMap<String, Object>();
    	result.put("code", ResponseCode.OK.getCode());
    	result.put("msg", ResponseCode.OK.getMessage());
    	result.put("success", true);
    	result.put("userId", entity.getUserId());
        return result;
    }
    
    @Override
    @CacheClear(pre="user{1.username}")
    public void updateSelectiveById(User entity) {
        super.updateSelectiveById(entity);
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    public User getUserByUsername(String username){
        User user = new User();
        user.setUsername(username);
        return mapper.selectOne(user);
    }

	public int addUser(User entity) {
		return mapper.addUser(entity);
	}
	public TableResultResponse<User> pageList(@RequestBody QueryPersonalBaseListRequest bean){
		Example example = new Example(User.class);
		Criteria criteria = example.createCriteria();
		if(!"".equals(bean.getPlatformId()) && null != bean.getPlatformId()){
			//是平台管理员
			criteria.andEqualTo("platformId", bean.getPlatformId());
		}else {
			//系统管理员
		}
		if(!"".equals(bean.getName()) && null != bean.getName()){
			criteria.andLike("name", "%" + bean.getName() + "%");
		}
		
		Page<User> result = PageHelper.startPage(bean.getPage(), bean.getLimit());
		List<User> list = mapper.selectByExample(example);
		return new TableResultResponse<User>(result.getTotal(), list);
	}
	
//	public static void main(String[] args){
//		String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex("123456".getBytes())+UserConstant.PW_MD5_SALT).getBytes());
//		log.info("加密md5Password的密码:" + md5Password);
//		String passwordEncoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
//		log.info("bcrypt密码:" + passwordEncoder);
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);
//        log.info("bcrypt密码对比:" + encoder.matches(md5Password, passwordEncoder));
//
//    }
	
	/**
	 * 修改用户密码
	 * @author centerroot
	 * @time 创建时间:2018年8月27日下午3:03:22
	 * @param req
	 * @return
	 */
    public Map<String, Object> updateUserPwd(UserPassword req) {
    	log.info("修改用户密码请求参数:{}",EntityUtils.beanToMap(req));
    	Map<String, Object> respMap = new HashMap<String, Object>();
    	User queryUser=new User();
    	queryUser.setUserId(Long.valueOf(req.getUserId()));
    	User user = mapper.selectOne(queryUser);
    	if (user == null) {
    		respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
            respMap.put("msg", ResponseCode.USERINFO_NOTEXIST.getMessage());
            log.info("修改用户密码响应参数:{}",respMap);
    		return respMap;
		}
    	String md5OldPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(req.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
    	
    	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);
        log.info("bcrypt密码对比:" + encoder.matches(md5OldPassword, user.getPassword()));
        if (encoder.matches(md5OldPassword, user.getPassword())) {
        	String md5NewPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(req.getNewPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
            String NewPassword = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5NewPassword);
            user.setPassword(NewPassword);
            mapper.updateByPrimaryKeySelective(user);
            respMap.put("code", ResponseCode.OK.getCode());
            respMap.put("msg", ResponseCode.OK.getMessage());
		}else{
            respMap.put("code", ResponseCode.USERINFO_PWD_ERROR.getCode());
            respMap.put("msg", ResponseCode.USERINFO_PWD_ERROR.getMessage());
		}
    	log.info("修改用户密码响应参数:{}",respMap);
		return respMap;
    }
    
    /**
     * 重置用户密码
     * @author centerroot
     * @time 创建时间:2018年8月27日下午3:31:55
     * @param req
     * @return
     */
    public Map<String, Object> resetUserPwd(UserPassword req) {
    	log.info("重置用户密码请求参数:{}",EntityUtils.beanToMap(req));
    	Map<String, Object> respMap = new HashMap<String, Object>();
    	//User user = mapper.selectByPrimaryKey(req.getId());
    	User queryUser=new User();
    	queryUser.setUserId(Long.valueOf(req.getUserId()));
    	User user = mapper.selectOne(queryUser);
    	if (user == null) {
    		respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
            respMap.put("msg", ResponseCode.USERINFO_NOTEXIST.getMessage());
            log.info("修改用户密码响应参数:{}",respMap);
    		return respMap;
		}
    	
    	String md5NewPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex("123456".getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String NewPassword = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5NewPassword);
        user.setPassword(NewPassword);
        mapper.updateByPrimaryKeySelective(user);
        respMap.put("code", ResponseCode.OK.getCode());
        respMap.put("msg", ResponseCode.OK.getMessage());
        
    	log.info("重置用户密码响应参数:{}",respMap);
		return respMap;
    }
}
